package net.sf.window.scope.tl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import net.sf.window.scope.WindowScope;

public class CreateWindowScope extends TagSupport
{
	private static final long serialVersionUID = -3787674813247296580L;
	private static final String NEW_LINE = "\n";
	private static final String SCRIPTS_PACKAGE = "net/sf/window/scope/tl/scripts/";
	
	private boolean dynamicFormScopingEnabled = true;
	private boolean windowScopeFlowEnabled = true;
	
	private static Map<String, String> scriptMapping = new HashMap<String, String>();
	
	@Override
	public int doStartTag() throws JspException 
	{
		Object existingWindowScopeId = pageContext.getRequest().getParameter(WindowScope.WINDOW_SCOPE_NAME);
		
		if(existingWindowScopeId==null || !windowScopeFlowEnabled)
			WindowScopeRegistry.createWindowScope();
		else
			WindowScopeRegistry.setWindowScope(String.valueOf(existingWindowScopeId));
		
		try 
		{
			
			JspWriter writer = pageContext.getOut();
			//TODO: add support for dojo
			//TODO: add some way to register your own library.
			//TODO: make sure all the header addition allows more headers to 
			// be passed in on an individual request (this probably will not work in DWR and prototype).
			
			StringBuilder out = new StringBuilder("<script type='text/javascript'>").append(NEW_LINE);
				
				out.append("var _windowScopeId='").append(WindowScopeRegistry.getWindowScope()).append("';").append(NEW_LINE);
				out.append("var _windowScopeName='").append(WindowScope.WINDOW_SCOPE_NAME).append("';").append(NEW_LINE);
		
				if (dynamicFormScopingEnabled)
				{
					writeScipt("dynamicFormScoping.js", out);
				}
				writeScipt(SCRIPTS_PACKAGE + "jQueryAjax.js", out);
				writeScipt(SCRIPTS_PACKAGE + "dwrAjax.js", out);
				writeScipt(SCRIPTS_PACKAGE + "prototypeAjax.js", out);
				writeScipt(SCRIPTS_PACKAGE + "YUI2Ajax.js", out);
				
			out.append("</script>");
			
			writer.write(out.toString());
		}
		catch (Exception e) 
		{
			throw new JspException(e.getMessage(), e);
		}
		return EVAL_PAGE;
	}
	private void writeScipt(String scriptFileName, StringBuilder out)
	{
		String cachedValue = scriptMapping.get(scriptFileName);
		if (cachedValue == null)
		{
			URL url = this.getClass().getClassLoader().getResource(scriptFileName);
			cachedValue = writeUrlToString(url);
			scriptMapping.put(scriptFileName, cachedValue);
		}
		out.append(NEW_LINE).append(cachedValue);
	}
	private String writeUrlToString(URL url)
	{
		StringBuilder builder = new StringBuilder();
		try
		{
			URLConnection connection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{
				builder.append(NEW_LINE);
				builder.append(inputLine);
			}
			in.close();
		}
		catch (Exception e)
		{
			
		}
		return builder.toString();
	}
	
	public void setDynamicFormScopingEnabled(boolean dynamicFormScopingEnabled) 
	{
		this.dynamicFormScopingEnabled = dynamicFormScopingEnabled;
	}
	

	public void setWindowScopeFlowEnabled(boolean windowScopeFlowEnabled) 
	{
		this.windowScopeFlowEnabled = windowScopeFlowEnabled;
	}
}
